<template>
  <div class="login-container">
    <el-card :body-style="{ padding: '40px' }">
      <div class="logo-container">
        <img class="logo" src="@/assets/images/logo.png" alt="logo" />
      </div>
  <el-form ref="loginFormRef" :model="loginForm"  :rules="ruleArr" >
  <el-form-item prop="mobile">
    <el-input v-model="loginForm.mobile" placeholder="手机号"></el-input>
  </el-form-item>
   <el-form-item prop="code">
    <el-input v-model="loginForm.code"  placeholder="验证码"></el-input>
  </el-form-item>
  <el-form-item>
      <el-checkbox v-model="isAgree" label="我已阅读并同意「用户协议」和「隐私条款」"></el-checkbox>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="onSubmitFn">登录</el-button>
  </el-form-item>
</el-form>
    </el-card>
  </div>
</template>

<script>
import { setToken } from '@/utils/token'
import { loginAPI } from '@/api/Login'
export default {
  // 给组件命名,Vue调试工具显示标签名为组件名
  name: 'Login',
  data () {
    return {
      isAgree: false,
      loginForm: {
        mobile: '15001264160',
        code: '246810'
      },
      ruleArr: {
        mobile: [{
          required: true,
          message: '手机号不能为空',
          trigger: 'blur'

        }, {
          pattern: /^1[3-9]\d{9}$/,
          message: '请输入正确手机号',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '验证码不能为空',
          trigger: 'change'
        }, {
          pattern: /^\d{6}$/,
          message: '请输入正确验证码',
          trigger: 'change'
        }]
      }
    }
  },
  methods: {
    onSubmitFn () {
      if (!this.isAgree) {
        this.$message({
          message: '登录前,请同意用户协议',
          type: 'warning'
        })
        return
      }
      // 1.做一个整体校验,通过了再发请求
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return

        try {
          // 2.调用接口
          const resp = await loginAPI(this.loginForm)
          // 3.成功提示
          this.$message({
            type: 'success',
            message: '登陆成功'
          })
          // 4.存储token到本地
          setToken(resp.data.data.token)
          // 5.自动跳转到首页 -> 编程式导航
          this.$router.replace('/') // replace不可以回退
          // this.$router.push('/') //push可以回退->添加到历史记录
          // 也可以写作 this.$router.push({path:'/'})
        } catch (e) {
          this.$message({
            type: 'error',
            message: '手机号或验证码输入有误'
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url(~@/assets/images/login.png);
  .el-card {
    width: 440px;
    height: 380px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 50px rgba(0, 0, 0, 0.1);
    .logo {
      width: 200px;
      display: block;
      margin: 0 auto 20px;
    }
    .el-button {
      width: 100%;
    }
  }
}
</style>
